import React from 'react'
import axios from 'axios'

function Index() {
  const [messages, setMessages] = React.useState<{ role: 'user' | 'assistant'; content: string }[]>([])
  const [input, setInput] = React.useState('')
  const [sending, setSending] = React.useState(false)
  const [conversationId, setConversationId] = React.useState<string | undefined>(undefined)
  const scrollRef = React.useRef<HTMLDivElement | null>(null)

  React.useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight
    }
  }, [messages])

  const callCoze = async (text: string): Promise<string> => {
    const resp = await axios.post('/coze/chat', { text, conversationId })
    const data = resp.data || {}
    const cid = data.conversationId || data.conversation_id
    if (cid && !conversationId) setConversationId(cid)
    return data.answer || '未获取到回复'
  }

  const handleSend = async () => {
    const content = input.trim()
    if (!content || sending) return
    setInput('')
    const next = [...messages, { role: 'user', content }]
    setMessages(next)
    setSending(true)
    try {
      const reply = await callCoze(content)
      setMessages((prev) => [...prev, { role: 'assistant', content: reply }])
    } catch (e) {
      setMessages((prev) => [...prev, { role: 'assistant', content: '调用失败，请稍后重试' }])
    } finally {
      setSending(false)
    }
  }

  const handleKeyDown: React.KeyboardEventHandler<HTMLTextAreaElement> = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSend()
    }
  }

  return (
    <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', background: 'linear-gradient(180deg,#f7f9fc,#ffffff)' }}>
      <div style={{ position: 'sticky', top: 0, zIndex: 10, background: 'rgba(255,255,255,0.8)', backdropFilter: 'saturate(180%) blur(8px)', borderBottom: '1px solid #eee' }}>
        <div style={{ maxWidth: 960, margin: '0 auto', padding: '12px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            <div style={{ fontSize: 18, fontWeight: 700 }}>智能体对话</div>
            <div style={{ fontSize: 12, color: '#888' }}>{conversationId ? `会话：${conversationId}` : '新会话'}</div>
          </div>
        </div>
      </div>

      <div style={{ flex: 1, width: '100%' }}>
        <div style={{ maxWidth: 960, margin: '0 auto', padding: 16, boxSizing: 'border-box', height: '100%' }}>
          <div style={{ display: 'flex', flexDirection: 'column', height: 'calc(100vh - 120px)' }}>
            <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', background: '#fff', border: '1px solid #eee', borderRadius: 12, padding: 16 }}>
              {messages.length === 0 ? (
                <div style={{ color: '#888', textAlign: 'center', padding: '48px 0' }}>开始你的提问吧</div>
              ) : (
                messages.map((m, idx) => (
                  <div key={idx} style={{ display: 'flex', gap: 8, marginBottom: 14, alignItems: 'flex-end', flexDirection: m.role === 'user' ? 'row-reverse' : 'row' }}>
                    <div style={{ width: 32, height: 32, borderRadius: '50%', background: m.role === 'user' ? '#1677ff' : '#10b981', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14 }}>
                      {m.role === 'user' ? '我' : '智'}
                    </div>
                    <div style={{ maxWidth: '78%', padding: '10px 12px', borderRadius: 12, background: m.role === 'user' ? '#1677ff' : '#f6f7f9', color: m.role === 'user' ? '#fff' : '#222', border: m.role === 'user' ? 'none' : '1px solid #eee', whiteSpace: 'pre-wrap', lineHeight: 1.7 }}>
                      {m.content}
                    </div>
                  </div>
                ))
              )}
            </div>

            <div style={{ display: 'flex', gap: 10, marginTop: 12, alignItems: 'flex-start' }}>
              <textarea
                value={input}
                onChange={(e) => setInput(e.target.value)}
                onKeyDown={handleKeyDown}
                disabled={sending}
                placeholder={sending ? '发送中…' : '输入你的问题，Enter 发送，Shift+Enter 换行'}
                rows={1}
                style={{ flex: '0 1 720px', maxWidth: 720, width: '100%', padding: '10px 12px', border: '1px solid #ddd', borderRadius: 10, outline: 'none', fontSize: 14, background: sending ? '#fafafa' : '#fff', resize: 'vertical' }}
              />
              <button
                onClick={handleSend}
                disabled={sending || !input.trim()}
                style={{ padding: '12px 18px', borderRadius: 10, border: 'none', background: sending || !input.trim() ? '#b8d1ff' : '#1677ff', color: '#fff', cursor: sending || !input.trim() ? 'not-allowed' : 'pointer', fontWeight: 600 }}
              >
                发送
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default Index
